package com.app.bimo.commonbusiness.network;

import android.util.Log;

import com.app.bimo.commonbusiness.network.Exception.ApiException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;

public class GsonUtil {
    public static <T> T convert(ResponseBody value, Gson gson, Charset UTF_8, TypeAdapter<T> adapter) throws IOException {
        try {
            String response = value.string();
            Log.i("CustomGsonResponse", "convert: " + response);
            JSONObject mJSONObject = null;
            try {
                mJSONObject = new JSONObject(response);
            } catch (JSONException mE) {
                throw new IOException(mE.getMessage());
            }
            int code = mJSONObject.optInt("code", -1);
            if (code == 200) {
                MediaType mediaType = value.contentType();
                Charset charset = mediaType != null ? mediaType.charset(UTF_8) : UTF_8;
                InputStream inputStream = new ByteArrayInputStream(response.getBytes());
                JsonReader jsonReader = gson.newJsonReader(new InputStreamReader(inputStream, charset));
                T result = adapter.read(jsonReader);
                if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                    throw new IOException("JSON document was not fully consumed.");
                }
                return result;
            } else {
                String message = mJSONObject.optString("msg");
                value.close();
                throw new ApiException(code, message);
            }

        } finally {
            value.close();
        }
    }


    public static ResponseBody buffer(final ResponseBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.source().readAll(buffer);
        return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
    }

}
